<template>
  <el-dialog v-model="dialogVisible" title="分享文件" :fullscreen="isMobile">
    <el-form :model="form" label-width="auto" :v-loading="true">
      <el-form-item label="有效时间">
        <el-select v-model="form.aging" placeholder="Select">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提取码">
        <el-input v-model="form.pwd" placeholder="请输入提取码" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="successDialogVisible"
    title="分享文件"
    :fullscreen="isMobile"
  >
    <template #header>
      <el-alert
        title="分享成功, 可在“我的分享”中查看。"
        type="success"
        show-icon
        :closable="false"
      />
    </template>
    <el-descriptions title="详情信息">
      <el-descriptions-item label="">
        <svg class="file-icon" aria-hidden="true">
          <use :xlink:href="`#${getFileIconId(file.type)}`" />
        </svg>
        {{ file.filename }}
      </el-descriptions-item>
      <el-descriptions-item label="分享人">{{
        shareInfo.userId
      }}</el-descriptions-item>
      <el-descriptions-item label="失效时间">{{
        formatToDateTime(shareInfo?.expires)
      }}</el-descriptions-item>
      <el-descriptions-item label="分享链接">
        <div @click="onCopyUrl">
          <el-text type="primary"
            >{{ getShareUrl()
            }}<el-icon ><CopyDocument /></el-icon
          ></el-text>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="提取码">
        <el-tag @click="onCopypwd"
          >{{ shareInfo?.pwd
          }}<el-icon ><CopyDocument /></el-icon
        ></el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="successDialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="onCopy">复制链接+提取码</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, computed } from "vue";
import { getFileIconId } from "../utils/FileIconId";
import { ElMessage } from "element-plus";
import { shareApi } from "../api";
import { formatToDateTime } from "../utils/FormatUtil";
import { ElLoading } from "element-plus";
import { useWindowSize } from "@vueuse/core";
const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);

const dialogVisible = ref(false);
const successDialogVisible = ref(false);

const file = ref(null);
let shareInfo = ref(null);

const form = ref({
  aging: "4",
  pwd: generateRandomString(),
});
const options = [
  { value: "1", label: "1小时" },
  { value: "2", label: "1天" },
  { value: "3", label: "1周" },
  { value: "4", label: "1月" },
  { value: "5", label: "1年" },
  { value: "6", label: "永久有效" },
];
function generateRandomString(length = 4) {
  const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

const onConfirm = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let expires;
  const now = new Date();
  switch (form.value.aging) {
    case "1": // 1小时
      expires = new Date(now.getTime() + 60 * 60 * 1000);
      break;
    case "2": // 1天
      expires = new Date(now.getTime() + 24 * 60 * 60 * 1000);
      break;
    case "3": // 1周
      expires = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
      break;
    case "4": // 1月
      const oneMonthLater = new Date(now);
      oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);
      expires = oneMonthLater;
      break;
    case "5": // 1年
      const oneYearLater = new Date(now);
      oneYearLater.setFullYear(oneYearLater.getFullYear() + 1);
      expires = oneYearLater;
      break;
    case "6": // 永久有效
      expires = null;
      break;
    default:
      expires = null;
      break;
  }
  try {
    const result = await shareApi(file.value.id, form.value.pwd, expires);
    shareInfo.value = result.data;
    successDialogVisible.value = true;
  } catch (error) {
    console.error(error);
  }
  dialogVisible.value = false;
  loading.close();
};

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage({
      message: "复制成功",
      type: "success",
    });
    return true;
  } catch (err) {
    ElMessage({
      message: "复制失败",
      type: "error",
    });
    return false;
  }
}

const getShareUrl = () => {
  return `${window.location.origin}/share/${shareInfo.value?.id}`;
};
const onCopyUrl = () => {
  copyToClipboard(getShareUrl());
};
const onCopypwd = () => {
  if (shareInfo.value.pwd) {
    copyToClipboard(shareInfo.value.pwd);
  }
};
const onCopy = () => {
  if (!shareInfo.value.pwd) {
    copyToClipboard(getShareUrl());
  } else {
    const fullUrl = `${getShareUrl()}?pwd=${shareInfo.value.pwd}`;
    copyToClipboard(fullUrl);
  }
};

const open = (row) => {
  file.value = row;
  dialogVisible.value = true;
};
const close = () => {
  dialogVisible.value = false;
};
defineExpose({
  open,
  close,
});
</script>
